<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        $category=new Admin_Model_MCategory();
        $bookCategory=$category->getAllCategories(array("_id","name"));
        $this->view->category=$bookCategory;

        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) && isset($mySession->username))
        {
            $this->view->username=$mySession->username;
            $this->view->uid=$mySession->uid;
        }
    }
    public function indexAction()
    {
        $this->_helper->layout()->setLayout('layout_home');

        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) || isset($mySession->username))
        {
            $uid=$mySession->uid;
            $this->view->login=1;
            $book=new Admin_Model_MBook();
            $recommend=$book->getRecommendBook($uid);
            if(count($recommend)>0)
            {
                $this->view->haveRecommend=1;
            }
        }

        // event
        $eventModel=new Community_Model_MEvent();
        $event=$eventModel->getEvents($total, 1, 5,40);
        $this->view->event=$event;

        // story
        $storyModel=new Community_Model_MStory();
        $story=$storyModel->getStories($total, 1, 5,40);
        $this->view->story=$story;

        // bookcomment
        $commentModel=new Community_Model_MBookComment();
        $comment=$commentModel->getComments($total, 1, 5,40);
        $this->view->comment=$comment;
    }

    public function purchaseAction()
    {
        $this->_helper->layout()->setLayout('layout_home_2');

        $uid='';
        $cid='';
        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) && isset($mySession->username))
        {
            $uid=$mySession->uid;
            $userModel=new Personal_Model_MUser();
            $this->view->personalinfo=$userModel->getPersonalInfo($uid);
            $this->view->friends=$userModel->getFriends($uid);
        }
        else if(isset($mySession->idcart))
        {
            $cid=$mySession->idcart;
        }
        else
        {
            $this->_redirect("");
            return;
        }
        $cartModel=new Personal_Model_MCart();
        $res=$cartModel->getBookInCart($uid,$cid);
        if(count($res) >0)
        {
            $request=$this->getRequest();
            $type=$request->getParam('typebuy');   // loai thao tac: 0 -> mua, 1 -> tang
            //echo 'kiem tra:'. $type;
            if((int)$type !=0 && (int)$type !=1)
            {
                $this->_redirect("");
                return;
            }
            //echo 'kiem tra:'. $type;
            // cap nhat lai thong tin ve mua va so luong sach
            $arrbook=array();

            // du lieu tu trang xem gio hang chuyen sang doi luc co loi
            // so luong tat ca sach deu bang =0
            // vi vay, $count de xac dinh co loi hay ko
            // neu so luong tat ca cac cuon sach deu bang 0 thi quay ve trang chu
            $count=0;    
            foreach($res as $book)
            {
                $id=$book["_id"];
                $chb=$request->getParam('chb'.$id,-1);
                if($chb=='on')
                    $chb=1;
                if($chb!=1 && $chb!=-1)
                {
                    $this->_redirect("");
                    return;
                }
                $number=(int)$request->getParam('txt'.$id);
                if(!is_int($number) || ((is_int($number) && ($number<0 || $number >20))))
                {
                    $this->_redirect("");
                    return;
                }
                if($number==0)
                    $count++;
                
                $abook=array("id_book"=>new MongoId($id),"check"=>$chb,"number"=>$number);
                array_push($arrbook, $abook);
            }
            // Neu co loi xay ra <=> tat ca cac cuon sach deu co so luong = 0
            if($count==count($res))
            {
                $this->_redirect("");
                return;
            }
            $cartModel->updateCart($uid, $cid, $arrbook);

            //
            $this->view->type=(int)$type;   // loai giao dich: mua (0) hay tang (1)
            $mySession->type=(int)$type;
            $mySession->setExpirationSeconds(3600, 'type');
            $this->view->uid=$uid;
            $this->view->cid=$cid;
            if($uid!='')
            {
                $this->view->typeuser=1;  // thuc hien thanh toan voi nguoi dung da dang nhap
            }
            else $this->view->typeuser=0; // thuc hien thanh toan voi nguoi dung public
        }
        else
            $this->_redirect("");
    }

    public function loginAction()
    {
        $this->_helper->layout()->setLayout('layout_home_2');
        $mySession=new Zend_Session_Namespace();
        if(!isset ($mySession->urlBack))
        {
            $mySession->urlBack=$this->getRequest()->getHeader("Referer");
            $mySession->setExpirationSeconds(3600, 'urlBack');
        }

        $user=$this->_getParam('username');
        $pass=$this->_getParam('password');
        if($user != null || $pass!=null)
        {
            $userModel=new Personal_Model_MUser();
            $uid=$userModel->login($user, $pass);
            if( $uid !='')
            {
                $mySession=new Zend_Session_Namespace();
                $mySession->uid=$uid;
                $userinfo=$userModel->getInfoBasic($uid);
                $mySession->username=$userinfo["user_name"];
                $mySession->setExpirationSeconds(3600, 'uid');
                $mySession->setExpirationSeconds(3600, 'username');
                echo $uid;
            }
            $this->getResponse()->clearBody();
            echo "Redirecting ... ";
            $this->_redirect($mySession->urlBack);
        }
    }

    private function isValidEmail($email)
    {
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
    }

    public function registerAction()
    {
        $this->_helper->layout()->setLayout('layout_home_2');

        $mySession=new Zend_Session_Namespace();
        if(isset($mySession->uid))
        {
            $this->_redirect("");
        }
        $request=$this->getRequest();
        
        $user=$request->getParam('username','');
        $pass=$request->getParam('pass','');
        $sex=(int) $request->getParam('sex',0);
        $firstname=$request->getParam('firstname','');
        $lastname=$request->getParam('lastname','');
        $day=(int)$request->getParam('day',0);
        $month=(int)$request->getParam('month',0);
        $year=(int)$request->getParam('year',0);
        $pin=$request->getParam('pid','');
        $phone=$request->getParam('phone','');
        $email=$request->getParam('email','');
        $address=$request->getParam('address','');
        
        if($user!='' && $pass!='' && checkdate($month, $day, $year) && ($sex==0 || $sex==1) && $this->isValidEmail($email))
        {
            $arr=array('year'=>$year,'month'=>$month,'day'=>$day);
            $date=new Zend_Date($arr);
            $newUser=array("user_name"=>$user,"password"=>$pass,"firstname"=>$firstname,"lastname"=>$lastname,"sex"=>$sex,
                "birthday"=>$date->__toString(),"pin"=>$pin,"phone"=>$phone,"email"=>$email,"address"=>$address,
                "image"=>  Zend_Controller_Front::getInstance()->getBaseUrl().'/images/avatar.jpg');

            $userModel=new Personal_Model_MUser();
            $uid=$userModel->register($newUser);
            if($uid!=FALSE)
            {
                $mySession=new Zend_Session_Namespace();
                $mySession->uid=$uid;
                $mySession->username=$user;
                $mySession->setExpirationSeconds(1200, 'uid');
                $mySession->setExpirationSeconds(1200, 'username');

                $this->_redirect("");
            }
        }
    }

    public function logoutAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');
        $uid=$this->_getParam('user');

        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) && isset($mySession->username))
        {
            unset ($mySession->uid);
            unset ($mySession->username);
            unset ($mySession->urlBack);
            unset ($mySession->type);
            unset ($mySession->idcart);
            $this->_redirect("");
        }
    }

    public function payAction()
    {
        $this->_helper->layout()->setLayout('layout_home_2');
        $uid='';
        $cid='';
        $typebuy=null;
        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) && isset($mySession->username))
        {
            $uid=$mySession->uid;
        }
        else if(isset($mySession->idcart))
        {
            $cid=$mySession->idcart;
        }
        if(isset($mySession->type))
            $typebuy=(int)$mySession->type;

        if(($uid=='' && $cid=='') || ($typebuy != 0 && $typebuy !=1) )
        {
            $this->_redirect("");
            return;
        }
        $request=$this->getRequest();

        //--------------- lay thong tin nguoi mua----------------------------------
        $userBuy=array();
        //sex
        if((int)$request->getParam('sex')!=0 && (int)$request->getParam('sex')!=1)
        {
            $this->_redirect("");
            return;
        }
        $userBuy["sex"]=(int)$request->getParam('sex');
        //lastname
        if( $request->getParam('lastname')==null || strlen((string)$request->getParam('lastname')) ==0)
        {
            $this->_redirect("");
            return;
        }
        $userBuy["lastname"]=$request->getParam('lastname');
        //firstname
        if( $request->getParam('firstname')==null || strlen((string)$request->getParam('firstname'))==0)
        {
            $this->_redirect("");
            return;
        }
        $userBuy["firstname"]=$request->getParam('firstname');
        //phone
        if( $request->getParam('phone')==null || strlen((string)$request->getParam('phone')) ==0)
        {
            $this->_redirect("");
            return;
        }
        $userBuy["phone"]=(int)$request->getParam('phone');
        //email
        if( $request->getParam('email')==null || strlen((string)$request->getParam('email')) ==0)
        {
            $this->_redirect("");
            return;
        }
        $userBuy["email"]=$request->getParam('email');
        //addresss
        if($typebuy==0)    // mua sach
        {
            if( $request->getParam('address')==null || strlen((string)$request->getParam('address')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userBuy["address"]=$request->getParam('address');
        }

        //-----------------------------------------------------------------------------------

        //-------------------------------- lay thong tin nguoi duoc tang-------------------------
        $userReceive=array();
        $message="";
        if($typebuy==1)// tang sach
        {
            //sex1
            if((int)$request->getParam('sex1')!=0 && (int)$request->getParam('sex1')!=1)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["sex"]=(int)$request->getParam('sex1');
            //lastname1
            if( $request->getParam('lastname1')==null || strlen((string)$request->getParam('lastname1')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["lastname"]=$request->getParam('lastname1');
            //firstname1
            if( $request->getParam('firstname1')==null || strlen((string)$request->getParam('firstname1')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["firstname"]=$request->getParam('firstname1');
            //phone1
            if( $request->getParam('phone1')==null || strlen((string)$request->getParam('phone1')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["phone"]=$request->getParam('phone1');
            //email1
            if( $request->getParam('email1')==null || strlen((string)$request->getParam('email1')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["email"]=$request->getParam('email1');
            //addresss1
            if( $request->getParam('address1')==null || strlen((string)$request->getParam('address1')) ==0)
            {
                $this->_redirect("");
                return;
            }
            $userReceive["address"]=$request->getParam('address1');


            // message
            $message=$request->getParam('message');
        }

        $uidReceive='';
        if($uid!='')    // nếu là người đăng nhập hệ thống thì lấy uid bạn được tặng
        {
            $uidReceive=$request->getParam('friend','0');
        }
        //-------------------------------------------------------------------------------------------------
        $cartModel=new Personal_Model_MCart();
        if(!$cartModel->addOrder($uid, $cid, $userBuy, $uidReceive, $userReceive, $message, $typebuy))
        {
            echo ('<script type="text/javascript" language="javascript">alert("Lỗi đặt mua sách!");</script>');
            //$this->_redirect("");
            return;
        }
    }
}

